package cn.timelost.qy.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.timelost.qy.config.UploadConfig;
import cn.timelost.qy.controller.vo.FileQueryVo;
import cn.timelost.qy.dao.FileDao;
import cn.timelost.qy.entity.FileSave;
import cn.timelost.qy.service.FileService;
import cn.timelost.qy.util.IpUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * (FileSave)表服务实现类
 *
 * @author snatch-yi
 * @since 2024-08-05 15:03:47
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileDao fileDao;

    @Resource
    private UploadConfig uploadConfig;

    @Override
    public PageInfo<FileSave> queryByPage(@RequestParam FileQueryVo fileQueryVo) {
        PageHelper.startPage(fileQueryVo);
        List<FileSave> list = this.fileDao.queryAll(fileQueryVo);
        String address = IpUtil.getAddress();
        list.forEach(item -> item.setSnowName("http://" + address + ":" + uploadConfig.port + "/external/" + item.getSnowName()));
        return new PageInfo<>(list);
    }

    @Override
    public int insert(MultipartFile file, Long id) {
        String originName = file.getOriginalFilename();
        FileSave fileSave = new FileSave();
        fileSave.setSnowName(id + "." + FileUtil.getSuffix(originName));
        fileSave.setOriginName(originName);
        fileSave.setSize(file.getSize());
        return fileDao.insert(fileSave);
    }

    @Override
    public boolean deleteBySnowNames(List<String> snowNames) {
        return this.fileDao.deleteBySnowNames(snowNames) > 0;
    }

}
